package org.basis.algorithm.sort;

import org.basis.algorithm.common.SortUtil;

import java.util.Arrays;

/**
 * 选择排序
 *
 * @author wenpan 2024/03/03 23:36
 */
public class SelectionSort {

    public static void main(String[] args) {
        final int count = 10000;
        for (int i = 0; i < count; i++) {
            int[] nums = SortUtil.generateRandomArray(50, 10000);
            int[] copyArray = SortUtil.copyArray(nums);

            process(nums);
            Arrays.sort(copyArray);

            if (!SortUtil.isEqual(nums, copyArray)) {
                System.out.println("排序错误");
                break;
            }
        }
    }

    public static void process(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            // 记录最小位置下标(每一轮起始时都认为i位置是最小的)
            int index = i;
            // 从后续位置选择一个最小的来插入i位置
            for (int j = i; j < nums.length; j++) {
                if (nums[index] > nums[j]) {
                    index = j;
                }
            }
            // 交换
            SortUtil.swap(index, i, nums);
        }
    }
}
